/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package searchsort;

/**
 *
 * @author parallels
 */
public class BinarySearch {
    
    public static MyDataBean search(int key, MyDataBeanArray myArray) {
        
        // ascending order
        
        MyDataBean result = null;
        String message = "not found";
        
        int loIndex = 0;
        int hiIndex = myArray.size() - 1;
        int midIndex = -1;
        
        while (loIndex <= hiIndex) {
            midIndex = (loIndex + hiIndex) / 2;
            if (key > myArray.get(midIndex).getKey()) {
                loIndex = midIndex + 1;
            } else if (key < myArray.get(midIndex).getKey()) {
                hiIndex = midIndex - 1;
            } else {
                break;
            }
        }
        
        if (loIndex <= hiIndex) {
            result = myArray.get(midIndex);
            message = "founded at " + midIndex;
        }

        System.out.println(message);
        return result;
    }
    
}
